package com.ysd.lis.controller.sys;


import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ysd.common.Result;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.entity.LoginDto;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.service.SysUserDeptService;
import com.ysd.lis.service.SysUserService;
import com.ysd.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * cold_chain.t_user_dept 前端控制器
 * </p>
 *
 * @author Peng
 * @since 2021-10-08
 */
@Api(value = "用户部门")
@RestController
@RequestMapping("/api/user")
public class SysUserDeptController extends BaseController {
    @Autowired
    SysUserDeptService sysUserDeptService;
    @Autowired
    SysUserService sysUserService;
    @ApiOperation("获取用户部门列表")
    @GetMapping("/findUserDepts")
    public Result findUserDepts(@RequestParam String userId){
        return  sysUserDeptService.findUserDepts(userId);
    }

    @ApiOperation(value = "给手机端返回token")
    @GetMapping("/getUserToken")
    public Result getUserToken(LoginDto loginDto) {
        String username = loginDto.getUsername();
        if (StringUtils.isNotBlank(username)) {
            LambdaQueryWrapper<SysUser> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(SysUser::getUsername, username).eq(SysUser::getDelFlag, 0);
            List<SysUser> list = sysUserService.list(lambdaQueryWrapper);
            if (CollectionUtils.isNotEmpty(list) && list.size() > 0) {
                return Result.succ(1, "登录成功", MapUtil.builder()
                        .put("userId", list.get(0).getId())
                        .put("orgId", list.get(0).getOrgId())
                        .put("token", JwtUtils.createToken(username,  list.get(0).getId()))
                        .map()
                );
            } else {
                return Result.fail("用户不存在", null);
            }
        } else {
            return Result.fail("token错误！", null);
        }
    }

}
